﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using Newtonsoft.Json;
using T.FAS.Runtime.Base.Entity;
using System.Data;
using T.ServiceComponent.DAC.Service;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.Base.Dao
{
    public class FASRouterDao : DaoService<FASRouter>
    {
        public override string TableName => "fas_router";
        public override string IDColumnName => "ID";
        public override List<string> ExceptColumnName => ExceptColumnNames;

        private List<string> _excepColumnName;
        protected List<string> ExceptColumnNames
        {
            get
            {
                if (_excepColumnName == null)
                    _excepColumnName = DaoUtil.GetExceptionColumn<FASRouter>();
                return _excepColumnName;
            }
        }

        public FASRouterDao() : base()
        {
            DBName = "TMaster";
        } 

        /// <summary>
        /// 获取去重后的router表
        /// </summary>
        /// <returns></returns>
        public List<FASRouter> GetAllRouters()
        {
            string sql = "select ID,DevAppID,ServiceSetID from fas_router;";
            var ds = this.DB.ExecuteDataSet(sql);
            var dt = ds?.Tables?[0];
            if (dt == null) return null;
            return DaoUtil.ConvertToEntity<FASRouter>(dt, this.ExceptColumnName);
        }

        /// <summary>
        /// 根据集群类型获取Host信息
        /// </summary>
        public List<HostInfo> GetHostInfos(string clusterType)
        {
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@clusterType", TDbDataType.VarChar, clusterType));
            var sql = @"select host.HostIPAddress,host.Port,machine.HostName from acm_applicationhost host
            join ACM_ApplicationNode node on host.NodeID  = node.id
            join ACM_ApplicationCluster cluster on cluster.ID = host.ClusterID 
            join ACM_ServerMachine machine on node.ResourceID = machine.ID 
            where ClusterType =@clusterType";
            var ds = this.DB.ExecuteDataSet(sql, paramsList.ToArray());
            List<HostInfo> list = new List<HostInfo>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    HostInfo info = new HostInfo();
                    info.HostIPAddress = Convert.ToString(row["HostIPAddress"]);
                    info.Port = Convert.ToInt32(row["Port"]);
                    info.HostName = Convert.ToString(row["HostName"]);
                    list.Add(info);
                }
            }
            return list;
        }
    }
}
